package com.xnchat.pro.service;

import com.mysql.cj.util.StringUtils;
import com.xnchat.pro.dto.Nicktable;
import com.xnchat.pro.dto.OneYige;
import com.xnchat.pro.dto.User;
import com.xnchat.pro.enums.CMDLIST;
import com.xnchat.pro.mapper.NickTableRepository;
import com.xnchat.pro.mapper.OneYIgeRepository;
import com.xnchat.pro.mapper.UserRepository;
import com.xnchat.pro.utils.MyDrrrUtil;
import com.xnchat.pro.utils.NormalReturn;
import com.xnchat.pro.vo.TalkMessage;
import com.xnchat.pro.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 小凝
 */
@Component
public class RobotHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private MyDrrrUtil myDrrrUtil = new MyDrrrUtil();
    private OneYIgeRepository oneYIgeRepository;
    private UserRepository userRepository;
    private static String HELP = "message=:/me#dqrp 当前人品|/me#tw 随机图文#cym 曾用名【待更新】||/me#welcome:这里写你希望的欢迎台词||/me#xb? ?分钟下班倒计时||/me#我爱加班 关闭倒数||#添加人类语录#这是一个留言功能;#人类语录#随机查看留言";
    private NickTableRepository nickTableRepository;
    private ClockService clockService;
    public static Boolean welComeFlag = true;
    @Value("${user.admin.name}")
    private String adminName;

    //这里面插入命令
    public void huiDa(UserVo user, String message, String code) {
        if (message == null || "".equals(message.trim())) return;
        if (adminName.equals(user.getName())) return;
        if (CMDLIST.Random.getValue().equals(message)) {
            String rp = "@" + user.getName() + " 当前人品值：" + ThreadLocalRandom.current().nextInt(101);
            myDrrrUtil.sendMessage(code, rp);
        } else if (CMDLIST.TUWEN.getValue().equals(message)) {
            myDrrrUtil.normalSend(code, sendPicture());
        } else if (CMDLIST.HISTORYNAME.getValue().equals(message)) {
            myDrrrUtil.normalSend(code, sendHistoryCode(user));
        } else if (CMDLIST.HELP.getValue().equals(message)) {
            myDrrrUtil.normalSend(code, HELP);
        } else if (CMDLIST.CLOCKON.getValue().equals(message)) {
            //报时功能暂时不加了吧。多线程逻辑没想好
        } else if (CMDLIST.CLOCKOFF.getValue().equals(message)) {

        } else if (message.contains(CMDLIST.XIABAN_TYPE.getValue())) {
            int time;
            try {
                time = Integer.parseInt(message.substring(3));
            } catch (Exception e) {
                myDrrrUtil.normalSend(code, "message=不要带空格，正确命令格式,例  /me#xb30");
                return;
            }
            NormalReturn normalReturn = clockService.addClock(user.getName(), time, code, CMDLIST.XIABAN_TYPE.getCode());
            myDrrrUtil.sendMessage(code, user.getName() + normalReturn.getMessage());
        } else if (CMDLIST.XBSB.getValue().equals(message)) {
            NormalReturn normalReturn = clockService.stopClock(CMDLIST.XIABAN_TYPE.getCode());
            myDrrrUtil.sendMessage(code, user.getName() + normalReturn.getMessage());
        } else if (message.indexOf(CMDLIST.WELCOME.getValue()) == 0) {
            String line = message.substring(9);
            if (line.contains("#")) {
                myDrrrUtil.sendMessage(code, "请勿使用#关键字");
                return;
            }
            if (StringUtils.isNullOrEmpty(user.getTripcode())) {
                myDrrrUtil.sendMessage(code, "no tc,no special");
                return;
            }
            try {
                nickTableRepository.insertOrUpdate(user.getTripcode(), line);
                myDrrrUtil.sendMessage(code, "修改成功@" + user.getName());
            } catch (Exception e) {
                myDrrrUtil.sendMessage(code, "修改失败@" + user.getName());
                e.printStackTrace();
            }


        }
    }

    public void MingLing(UserVo user, TalkMessage msg, String code) {
        String message = msg.getMessage().trim();
        if (StringUtils.isNullOrEmpty(message) || StringUtils.isNullOrEmpty(code)) return;
        if ("#leave#".equals(message)) {
            String leave = "message=/leave";
            myDrrrUtil.normalSend(code, leave);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            myDrrrUtil.normalSend(code, "message=退出失败");
        } else if ("#host#".equals(message) && user.getTripcode() != null) {
            List<User> flag = userRepository.findAllBytripcode(user.getTripcode());
            if (flag.size() > 0) {
                myDrrrUtil.normalSend(code, "new_host=" + user.getId());
                logger.info("房主转让给 {}", user.getName());
            }
        } else if (message.indexOf(CMDLIST.TJRLYL.getValue()) == 0) {
            message = message.substring(8).trim();
            if (message.indexOf("#") == 0) {
                message = "{" + message + "}---" + user.getName();
            }
            String url = msg.getUrl();
            if (StringUtils.isNullOrEmpty(url)) {
                url = "";
            }
            OneYige oneYige = new OneYige();
            oneYige.setBody(message);
            oneYige.setUrl(url);
            oneYige.setType(CMDLIST.TYPE_YL.getCode());
            oneYIgeRepository.save(oneYige);
            myDrrrUtil.sendMessage(code, "正常的语录添加成功");
        } else if (message.indexOf(CMDLIST.RLYL.getValue()) == 0) {
            int count = oneYIgeRepository.countAllByType(CMDLIST.TYPE_YL.getCode());
            if (count < 1) {
                logger.warn("语录查询失败，莫得数据");
                return;
            }
            int yl = ThreadLocalRandom.current().nextInt(count);
            Pageable page = PageRequest.of(yl, 1);
            Page<OneYige> byType = oneYIgeRepository.findByType(CMDLIST.TYPE_YL.getCode(), page);
            OneYige oneYige = byType.getContent().get(0);
            String re = "message=%s&url=%s";
            String url = StringUtils.isNullOrEmpty(oneYige.getUrl()) ? "http://mei.you.wang.zhi" : oneYige.getUrl();
            re = String.format(re, oneYige.getBody(), url);
            myDrrrUtil.normalSend(code, re);
        }
    }


    public void welcome(UserVo user, String code) {
        if (!welComeFlag) return;
        String send;
        //这里加一个用户判断的工具
        send = String.format(randomWelcome(), user.getName());
        if (!StringUtils.isNullOrEmpty(user.getTripcode())) {
            List<Nicktable> allByTripcode = nickTableRepository.findAllByTripcode(user.getTripcode());
            if (allByTripcode.size() > 0) {
                send = allByTripcode.get(0).getWelcomeline();
            }
        }
        myDrrrUtil.sendMessage(code, send);
    }

    /**
     * 随机欢迎
     *
     * @return
     */
    private static String randomWelcome() {
        int i = riAn();
        String re = "";
        switch (i) {
            case 0:
                re = " 上午好，摸鱼快乐~ @%s";
                break;
            case 1:
                re = "下午好，今天有好好摸鱼吗 @%s  ";
                break;
            case 2:
                re = "晚上好，小凝大概率已经不在线了，如果你是房主，记得离开时关好房间 @%s ";
                break;

            default:
                re = "welcome to tf room @%s ";
                break;
        }
        return re;
    }

    public static void main(String[] args) {
        System.out.println(riAn());
    }

    private static int riAn() {
        Calendar ri = Calendar.getInstance();
        int i = ri.get(Calendar.AM_PM);
        if (Calendar.AM == i) {
            return 0;
        } else {
            Calendar yewan = Calendar.getInstance();
            yewan.set(Calendar.HOUR_OF_DAY, 18);
            if (yewan.compareTo(ri) > 0) {
                return 1;
            }
            return 2;
        }
    }

    private String sendPicture() {
        int count = oneYIgeRepository.countAllByType(0);
        int id = new Random().nextInt(count);
        List<OneYige> allById = oneYIgeRepository.findAllById(Collections.singleton(id));
        String message = "message=%s&url=%s";
        if (allById.size() > 0) {
            OneYige oneYige = allById.get(0);
            message = String.format(message, oneYige.getBody(), oneYige.getUrl());
        } else {
            message = "err";
        }
        return message;
    }

    private String sendHistoryCode(UserVo u) {
        String tripcode = u.getTripcode();
        if (StringUtils.isNullOrEmpty(tripcode)) {
            return "message=该功能仅供tc用户使用&to=" + u.getId();
        }
        List<User> allByTripCode = userRepository.findAllBytripcode(tripcode);
        if (allByTripCode.size() < 1) {
            return "massage=未查询到数据&to=" + u.getId();
        }
        StringBuffer re = new StringBuffer("to=" + u.getId() + "&message=曾用名:");
        allByTripCode.forEach(c -> re.append(c.getUsername()).append(" # "));
        return re.toString();
    }

    @Autowired
    public void setOneYIgeRepository(OneYIgeRepository oneYIgeRepository) {
        this.oneYIgeRepository = oneYIgeRepository;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setNickTableRepository(NickTableRepository nickTableRepository) {
        this.nickTableRepository = nickTableRepository;
    }

    @Autowired
    public void setClockService(ClockService clockService) {
        this.clockService = clockService;
    }


}
